package org.softmed.rest.server.defaults.generation;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.softmed.filehandling.FileUtil;
import org.softmed.reflection.utils.ReflectionUtil;
import org.softmed.rest.generation.scafold.AppConfig;
import org.softmed.rest.generation.scafold.ModConfig;
import org.softmed.rest.generation.scafold.build.DirectoryReader;

public class DefaultDirectoryReader implements DirectoryReader {

	ReflectionUtil reflect = new ReflectionUtil();

	@Override
	public List<AppConfig> getApps(String rootDir) throws Throwable {

		List<AppConfig> apps = new ArrayList<AppConfig>();
		List<File> appDirs = new ArrayList<File>();

		List<String> appNames = new ArrayList<String>();

		FileUtil util = new FileUtil();
		File file = util.getFile(rootDir);
		File[] childs = file.listFiles();

		if (childs != null)
			for (File child : childs) {
				if (child.isDirectory())
					appDirs.add(child);
			}

		AppConfig app = null;
		for (File child : appDirs) {
			app = new AppConfig();
			String name = reflect.getHifenizedName(child.getName());
			if (appNames.contains(name))
				throw new RuntimeException("Application name " + name
						+ " already registered : " + child.getCanonicalPath());
			app.setPath(child.getCanonicalPath());
			app.setName(name);
			appNames.add(name);
			getModules(child, app);
			apps.add(app);
		}

		return apps;
	}

	private void getModules(File file2, AppConfig app) throws Throwable {
		File[] files = file2.listFiles();
		for (File file : files) {
			if (file.getName().equals("modules") && file.isDirectory())
				getModuleList(file, app);
		}

	}

	private void getModuleList(File file, AppConfig app) throws Throwable {
		File[] files = file.listFiles();

		List<String> modNames = new ArrayList<String>();

		for (File file2 : files) {
			if (file2.isDirectory()) {
				ModConfig mod = new ModConfig();
				String name = reflect.getHifenizedName(file2.getName());
				if (modNames.contains(name))
					throw new RuntimeException("Module name " + name
							+ " already registered : "
							+ file2.getCanonicalPath());

				mod.setPath(file2.getCanonicalPath());
				mod.setName(name);
				modNames.add(name);
				app.getModules().add(mod);
			}
		}

	}
}
